package com.google.code.irouter.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONObject;
import com.google.code.irouter.model.Model;
import com.google.code.irouter.model.Solution;
import com.google.code.irouter.portal.client.rpc.solution.SolutionResult;
import com.google.code.irouter.portal.server.SolutionServiceImpl;
import com.google.code.irouter.utils.DateTimeUtil;
import com.google.code.irouter.utils.ModelUtil;

public final class Log extends HttpServlet {

	private static final long serialVersionUID = -5546119560501036905L;

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		try{
			UserService userService = UserServiceFactory.getUserService();
			String thisURL = request.getRequestURI();
			if (request.getUserPrincipal() == null)
				response.sendRedirect(userService.createLoginURL(thisURL));
			String solutionId = request.getParameter("solution");
			if(solutionId.trim().length() == 0) {
				SolutionServiceImpl solutionServiceImpl = new SolutionServiceImpl();
				SolutionResult solutionResult = solutionServiceImpl.get();
				solutionId = solutionResult.getId();
			}
			if(solutionId.trim().length() == 0)
				return;		
			
			int limit = Integer.valueOf(request.getParameter("limit"));
			String dir = request.getParameter("dir");
			String sort = request.getParameter("sort");
			int start = Integer.valueOf(request.getParameter("start"));
			
			Map<String, Object> result = new HashMap<String, Object>();
			Map<String, SortDirection> order = new HashMap<String, SortDirection>();
			if(dir.equals("DESC"))
				order.put(sort, SortDirection.DESCENDING);
			else
				order.put(sort, SortDirection.ASCENDING);
			
			Map<String, Object> query = new HashMap<String, Object>();
			List<Key> solutionIdList = new ArrayList<Key>();
			solutionIdList.add(KeyFactory.createKey(Solution.class.getSimpleName(),Long.valueOf(solutionId)));
			solutionIdList.add(null);
			query.put("solution", solutionIdList);

			List<Model> objectList = ModelUtil.selectByOrderWithLimit(com.google.code.irouter.model.Log.class, query, order, start, limit);
			List<Model> objectListForCount = ModelUtil.select(com.google.code.irouter.model.Log.class, query);
			JSONArray items = new JSONArray();
			int index = 0;
			for(Model object : objectList) {
				com.google.code.irouter.model.Log log = (com.google.code.irouter.model.Log) object;
				JSONObject item = new JSONObject();
				item.put("key", String.valueOf(log.getKey().getId()));
				item.put("message", log.getMessage());
				item.put("stack", log.getStack());				
				item.put("category", log.getCategory());
				item.put("level", log.getLevel());
				item.put("sender", log.getSender());
				item.put("stack", log.getStack());
				item.put("createDate", DateTimeUtil.formatDate(log.getCreateDate()));

				String solutionName = "";
				if(log.getSolution() != null) {
					List<Model> solutionList = ModelUtil.select(Solution.class, log.getSolution());
					if(solutionList.size() > 0)
						solutionName = ((Solution)solutionList.get(0)).getName();
				}
				item.put("solution", solutionName);				
				items.put(item);
				index++;
			}
			result.put("topics", items);
			
			JSONObject jsonDataToReturn = new JSONObject();
			jsonDataToReturn.put("totalCount", String.valueOf(objectListForCount.size()));
			jsonDataToReturn.put("topics", items);

			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/x-json;charset=UTF-8");
			response.getWriter().print(jsonDataToReturn.toString(1));
		} catch (Exception exception) {
			// TODO
			exception.printStackTrace();
		}

	}

}
